package com.duojuhe.common.extend.form.attribute;

import com.alibaba.fastjson.JSONArray;
import com.duojuhe.common.bean.BaseBean;
import com.duojuhe.common.utils.jsonutils.JsonUtils;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.apache.commons.lang3.StringUtils;

import javax.validation.constraints.NotBlank;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
public class AttributeParameter extends BaseBean {
    @ApiModelProperty(value = "属性参数值")
    private String value;

    @ApiModelProperty(value = "自定义属性标识", example = "deviceKey",required=true)
    @NotBlank(message = "自定义属性标识不能为空")
    private String key;


    /**
     * 把json字符串转成属性参数map对象
     *
     * @param attributeParameter
     */
    public static Map<String, AttributeParameter> getAttributeMap(String attributeParameter) {
        if (StringUtils.isBlank(attributeParameter)) {
            return new HashMap<>();
        }
        List<AttributeParameter> columnList = new ArrayList<>();
        try {
            if (StringUtils.isNotBlank(attributeParameter) && JsonUtils.isJson(attributeParameter)) {
                columnList = JSONArray.parseArray(attributeParameter, AttributeParameter.class);
            }
            return columnList.stream().collect(Collectors.toMap(AttributeParameter::getKey, account -> account));
        } catch (Exception e) {
            return new HashMap<>();
        }
    }

    /**
     * 自定义属性获取值
     */
    public static String getAttributeValueByKey(Map<String, AttributeParameter> map, String attributeKey) {
        if (map == null || StringUtils.isBlank(attributeKey)) {
            return StringUtils.EMPTY;
        }
        AttributeParameter attribute = map.get(attributeKey) ;
        if (attribute==null){
            return StringUtils.EMPTY;
        }
        return attribute.value;
    }
}